package com.wzh.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzh.store.entity.User;
import com.wzh.store.mapper.UserMapper;
import com.wzh.store.service.IUserService;
import com.wzh.store.service.ex.*;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

import static com.wzh.store.utils.EncryptionUtil.getMd5Password;

/**
 * @Author wzh
 * @create 2022/4/7 19:29
 * 用户模块业务层的实现类
 */
@Service
public class UserServiceimpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void reg(User user) {
        LambdaQueryWrapper<User> lqw =new LambdaQueryWrapper<User>();
        lqw.eq(User::getUsername,user.getUsername());
        User one = userMapper.selectOne(lqw);
        /*密码的加密处理:md5算法想形式，连续加载3次
         * 串+password+串
         * 盐值+password+盐值
         * */
        String password1 = user.getPassword();
//        获取盐值（随机生成一个盐值）
        String s = UUID.randomUUID().toString().toUpperCase();
//        将密码和盐值作为一个整体进行加密处理
        String md5Password = getMd5Password(password1, s);
//        将加密后的密码重新设置到user对象中
        user.setPassword(md5Password);
//        补全数据
        user.setSalt(s);//记录用户的盐值，当用户申请登录时将收到的密码再次进行加密3次，在查看是否与数据库中的密码相同，如果相同则登录成功
        user.setIsDelete(0);
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        Date date=new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);
        if (one==null){
            int insert = userMapper.insert(user);
            if (insert!=1){
                throw new InsertException("在用户注册过程中产生了未知的异常");
            }
        }else {
            throw new UsernameDuplicatedException("该用户名已经被占用");
        }
    }
//用户登录功能，返回当前匹配的用户数据，如果没有则返回null
    @Override
    public User login(String username, String password) {
        LambdaQueryWrapper<User> lw = new LambdaQueryWrapper<>();
        lw.eq(User::getUsername,username);
        User user = userMapper.selectOne(lw);
        if (user==null){
                throw new UserNotFoundException("该用户数据不存在");
        }
        String salt=user.getSalt();
        String newMd5Password=getMd5Password(password,salt);
        if (!newMd5Password.equals(user.getPassword())){
            throw new PasswordNotMatchException("密码错误xxxxxxx");
        }
//        判断逻辑删除子字段是否为1，如果逻辑删除字段为1则表名该用户已经注销或者该用户已经被删除
        if(user.getIsDelete()==1){
            throw new UserNotFoundException("用户数据不存在");
        }
//        返回一个user对象可以用于辅助其他的页面展示用户的头像，电话号码，名字等信息
//        在后台层与层之间的调用数据量越小，性能越高,数据体量越小，响应的速度也越高
        User user1=new User();
        user1.setUid(user.getUid());
        user1.setUsername(user.getUsername());
        user1.setAvatar(user.getAvatar());
        return user1;
    }
      //修改密码
    @Override
    public void changePassword(Integer uid, String username, String oldPassword, String newPassword) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUid,uid);
        User user1 = userMapper.selectOne(userLambdaQueryWrapper);
        if(user1==null||user1.getIsDelete()==1){
            throw new UserNotFoundException("用户数据不存在");
        }
//        原始密码和数据库中的密码进行比较
        String oldmd5Password = getMd5Password(oldPassword, user1.getSalt());
        if (!oldmd5Password.equals(user1.getPassword())){
            throw new PasswordNotMatchException("密码错误");
        }
//        将新的密码进行加密，在更新
      String newmd5Password = getMd5Password(newPassword, user1.getSalt());
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
                      userUpdateWrapper.eq("uid",uid);
                      User user=new User();
                      user.setPassword(newmd5Password);
                      user.setModifiedUser(username);
                      user.setModifiedTime(new Date());
        int update = userMapper.update(user, userUpdateWrapper);
        if(update!=1){
            throw new UpdateException("更新时产生未知的异常");
        }
    }

    /**
     * 
     * @param uid 获取修改资料页面所需
     * @return user对象,并不是dao层的对数据库简单的查询,为了将前端需要的信息展示给前端
     */
    @Override
    public User getUserByUid(Integer uid) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUid,uid);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        if (user==null||user.getIsDelete()==1){
            throw new UserNotFoundException("用户数据不存在");
        }
        User user1=new User();
        user1.setPhone(user.getPhone());
        user1.setEmail(user.getEmail());
        user1.setGender(user.getGender());
        user1.setUsername(user.getUsername());
        return user1;
    }

    /**
     *
     * @param uid 通过控制层的session获取
     * @param username 通过控制层的session获取
     * @param user 只封装了email、phone。gender
     */
    @Override
    public void chabgeInfo(Integer uid, String username, User user) {
        LambdaQueryWrapper<User> lwq = new LambdaQueryWrapper<User>();
        lwq.eq(User::getUid,uid);
        User user1 = userMapper.selectOne(lwq);
        if (user1==null||user1.getIsDelete()==1){
            throw new UserNotFoundException("用户数据不存在");
        }
        user.setUid(uid);
        user.setUsername(username);
        user.setModifiedUser(username);
        user.setModifiedTime(new Date());
        userMapper.updateInfoByUid(user);
    }

    @Override
    public void changeAvatar(Integer uid, String avatar, String modifiedUser) {
        Date modifiedTime=new Date();
        userMapper.updateAvatarByUid(uid,avatar,modifiedUser,modifiedTime);
    }
}
